package com.websocket2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    UserDetailsService configure() throws Exception{
        InMemoryUserDetailsManager manager=new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user1").password(passwordEncoder().encode("123")).roles("admin").build());
        manager.createUser(User.withUsername("user2").password(passwordEncoder().encode("123")).roles("user").build());
        return manager;
    }
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http.authorizeHttpRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll();

        //会话管理配置,设置一个用户只能建立一个会话
        http.sessionManagement()
                // 设置 Session 会话失效时重定向路径，默认为 loginPage()
                // .invalidSessionUrl("/login")
                // 配置使用自定义的 Session 会话失效处理策略
                //.invalidSessionStrategy(invalidSessionStrategy)
                // 设置单用户的 Session 最大并发会话数量，-1 表示不受限制
                .maximumSessions(1)
                // 设置为 true，表示某用户达到最大会话并发数后，新会话请求会被拒绝登录
                //.maxSessionsPreventsLogin(true)
                // 设置所要使用的 sessionRegistry，默认为 SessionRegistryImpl 实现类
                .sessionRegistry(sessionRegistry());
        return http.build();
    }

    @Bean //此顶配置后面用来获取所有登录用户
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

}
